<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>自动化部署界面</title>
  <link rel="stylesheet" type='text/css' href="/static/css/index.css" />
  <script type="text/javascript" src="/static/js/jquery.min.js"></script>
  <!--
  <link rel="stylesheet" type='text/css' href="/static/css/bootstrap-icons.css" />
  <script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="/static/js/bootstrap.bundle.min.js" ></script>
  -->
</head>



<body>

  <div class="container">
    <div class="operContainer">
      <button class="createBtn" id="createBtn">+ 新建</button>
      <div><input type="search" id='query' placeholder="根据按照客户名称搜索"/>&nbsp;&nbsp;<button class="searchBtn" onclick='search()'>搜索</button></div>
    </div>
    <table id="table">
      <thead>
        <tr>
          <th scope="col">客户名称</th>
          <th scope="col">软件版本</th>
          <th scope="col">cpu型号</th>
          <th scope="col">license</th>
          <th scope="col">发送邮箱</th>
          <th scope="col">操作</th>
        </tr>
      </thead>
      <tbody id="tableBody"></tbody>
    </table>
    <div class="pagination">
      <button class="prevPageBtn" id="prev">上一页</button>
      <span id="pageShow">1 / 5</span>
      <button class="nextPageBtn" id="next">下一页</button>
    </div>
    <div class="modal">
      <div class="mask" id="mask"></div>
      <div class="popup" id="popup">
        <div class="popupBox">
          <div class="popupHead">
            上传license
          </div>
          <hr />
          <div  class="popupContent">
            <form id="createForm" method="post">
                {% csrf_token  %}
              <div class="gridBox">
                <div><label>输入邮箱</label></div>
                <div><input name="email" placeholder="请输入" id="email"/></div>
                <div><label>选择版本</label></div>
                <div>
                  <select name="version" id="version">
{#                    <option value="2.2.6">2.2.6</option>#}
{#                    <option value="2.2.7">2.2.7</option>#}
{#                    <option value="2.3.1">2.3.1</option>#}
                  </select>
{#                    <select data-placeholder="选择项目..." class="form-control" name="update_project_name" id="update_project_name">#}
{#                        <option value="">请选择项目</option>s#}
{#                        　　{% for key,value in project.items %}#}
{#                        <option value="{{ value }}" hassubinfo="true">{{ key }}</option>#}
                        {# <option value="120000" hassubinfo="true">天津</option>#}
                        {# <option value="130000" hassubinfo="true">河北省</option>#}
{#                        　　{% endfor %}#}

                    </select>
                </div>
                <div><label>选择CPU</label></div>
                <div>
                  <select name="cpu" id="cpu">
                    <!--<option value="">--请选择--</option>-->
                    <option value="amd64">amd64</option>
                    <option value="arm64">arm64</option>
                  </select>
                </div>
                <div><label>上传license</label></div>
                <!--<div><input placeholder="请输入" type="file"/></div>-->
                <input type="file" name="myfile" id="file_select">

              </div>
              <div class="btnRow">
{#                <input type="submit" class="save" id="saveBtn" value='保存' />#}
                <input type="button" class="save" id="saveBtn" value='保存' onclick="add_data()" />
                <input type='reset' class="cancel" id="closeBtn" value='取消' />
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script type="text/javascript">
      const createBtn = document.getElementById('createBtn');
      createBtn.addEventListener('click', () => {
          const mask = document.getElementById('mask');
          const popup = document.getElementById('popup');
          {#location.reload()#}
          mask.style.display = 'block';
          popup.style.display = 'block';
          $.ajax({
              url: '/fmytest/getversion/', // 替换为真正的后台 URL
              type: 'GET',
              success: function (response) {
                  var $select = $('#version');
                  var parentElement = document.getElementById("version");
                  var childElements = parentElement.querySelectorAll("*");
                  childElements.forEach(function (child) {
                      parentElement.removeChild(child);
                  });
                  response.options.forEach(function (option) {
                      console.log(option, "字典")
                      $('<option></option>')
                          .attr('value', option.value)
                          .text(option.label)
                          .appendTo($select);
                  });
                   {#$select.selectpicker(); // 初始化 bootstrap-select 组件#}
              },
              error: function () {
                  console.log("Error occurred while fetching the data.");
              }
          });
      });
      const closeBtn = document.getElementById('closeBtn');
      closeBtn.addEventListener('click', () => {
          const mask = document.getElementById('mask');
          const popup = document.getElementById('popup');
          mask.style.display = 'none';
          popup.style.display = 'none';
      });


  </script>
  <script type="text/javascript">
      var totalPage = 0;
      var currentPage = 1;
      document.getElementById("query").addEventListener('keydown', (e) => {
          if (e.code === 'Enter') {
              currentPage = 1;
              getData(currentPage, e.target.value)
          }
      })


      function add_data() {
          var form_data = new FormData();
          var file_info = $('#file_select')[0].files[0]
          const email = $('#email').val();
          const version = $('#version').val();
          const cpu = $('#cpu').val();
          form_data.append('email', email);
          form_data.append('version', version);
          form_data.append('cpu', cpu);
          form_data.append('myfile', file_info);

          form_data.forEach(value => console.log(value))
          $.ajax({
              url: '/postdata/',
              type: 'POST',
              cache: false,
              data: form_data,
              processData: false, /* 告诉jquery不要处理数据，要加这个不然会报错，非法引用*/
              mimeType: "multipart/form-data",
              contentType: false,  /*告诉jquery不要设置contentType,要加这个*/
              success: function (res) {
                  const res_data = JSON.parse(res);
                  console.log(typeof res_data['messages']);
                  if (res_data['status']) {
                      alert(res_data['messages']);
                      document.getElementById('closeBtn').dispatchEvent(new MouseEvent('click'));
                      currentPage = 1;
                      getData(currentPage);
                  } else {
                      alert(res_data['messages']);
                  }

              }

          })
      }

      function search() {
          const query = $('#query').val();
          currentPage = 1;
          getData(currentPage, query);
      }

      function deleteItem(id) {
          const r = confirm("确定要删除这条数据吗？")
          if (r) {
              $.ajax({
                  url: `/deletedata/`,
                  type: 'post',
                  data: {
                      rid: id,
                      type: "del",
                  },
                  success: (res) => {
                      alert(res["messages"]);
                      currentPage = 1;
                      getData(currentPage);
                  },
                  error: () => alert('删除失败')
              })
          } else {
              currentPage = 1;
              getData(currentPage);
          }

      }
     function reGenerate(id) {
          console.log(id)
          const r = confirm("确定要重新生成安装包吗？")
          if (r) {
              $.ajax({
                  url: `/deletedata/`,
                  type: 'post',
                  data: {
                      rid: id,
                      type: "re",
                  },
                  success: (res) => {
                      alert(res["messages"]);
                      currentPage = 1;
                      getData(currentPage);
                  },
                  error: () => alert('重新生成失败')
              })
          } else {
              currentPage = 1;
              getData(currentPage);
          }

      }


      function sendMail(id) {
          console.log(id)
      }

      function getData(pageNum, query) {
          $.ajax({
              url: `/getdata/?pageNum=${pageNum}&pageSize=10${query ? `&query=${query}` : ''}`,
              type: 'get',
              success: (res) => {
                  console.log(res);
                  const {total, data} = res;
                  const rowDatas = JSON.parse(data);

                  totalPage = total;
                  writeList(rowDatas.map(item => ({id: item.pk, ...item.fields})));
                  changePagination();
              },
              error: () => {
                  alert("loadData Failed!!!");
              }
          });
      }

      function writeList(data) {
          const tableBody = document.getElementById('tableBody');
          console.log(data,'这里data');
          let trStr = '';

          const operationStr = ``;

          for (let i = 0; i < data.length; i += 1) {
              trStr += `<tr>
          <td>${data[i].name}</td>
          <td>${data[i].soft_version}</td>
          <td>${data[i].cpu}</td>
          <td>${data[i].license}</td>
          <td>${data[i].email}</td>
          <td class='operations'>
             <button class='deleteBtn' onclick="deleteItem('${data[i].id}')"><span><i class="bi bi-trash3"></i> 删除</span></button>&nbsp;
             <button  onclick="reGenerate('${data[i].id}')">重新生成</button>&nbsp;
             <button  onclick="sendMail('${data[i].id}')">发送邮件</button>
          </td>
        </tr>`;
          }
          tableBody.innerHTML = trStr;
      }

      $("#popup").ready(function () {

      });


      $('#prev').on('click', () => {
          if (currentPage > 1) {
              currentPage -= 1;
              getData(currentPage);
          } else {
              alert('当前为第一页！');
          }
      });
      $('#next').on('click', () => {
          if (currentPage < totalPage) {
              currentPage += 1;
              getData(currentPage);
          } else {
              alert('当前为最后一页！');
          }
      });

      function changePagination() {
          document.getElementById('pageShow').innerHTML = `${currentPage} / ${totalPage}`;
      }

      getData(currentPage);
  </script>
</body>

</html>
